<template>
  <div class="article-container">
    <div class="header">
      <el-button type="primary" class="add" @click="addArticleDialog">
        添加文章
      </el-button>
      <p>
        {{ form.content }}
      </p>
      <div class="search">
        <el-input v-model="input" placeholder="请输入内容"></el-input>
        <el-button type="success" @click="search"> 搜索 </el-button>
        <el-button type="info" @click="reset"> 重置 </el-button>
      </div>
    </div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column type="index" label="序号"> </el-table-column>

      <el-table-column prop="title" label="标题"> </el-table-column>

      <el-table-column prop="path_url" label="封面">
        <template #default="{ row }">
          <el-image
            style="width: 100px; height: 100px"
            :src="$API + '/' + row.path_url"
            fit="cover"
            :preview-src-list="[$API + '/' + row.path_url]"
          ></el-image>
        </template>
      </el-table-column>

      <el-table-column prop="cate_name" label="分类">
        <template #default="{ row }">
          {{ row.cate_name || '暂无分类' }}
        </template>
      </el-table-column>

      <el-table-column prop="content" label="内容">
        <template #default="{ row }">
          <el-link type="success" @click="showContent(row)">查看内容</el-link>
        </template>
      </el-table-column>

      <el-table-column prop="" label="操作">
        <template #default="{ row }">
          <el-button type="info" icon="el-icon-edit">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @current-change="pageClick"
      :page-size="pagesize"
      :current-page="page"
      background
      layout="prev, pager, next,total"
      :total="total"
    >
    </el-pagination>

    <!-- 添加文章的对话框 -->
    <el-dialog title="提示" :visible.sync="isShowAddForm">
      <el-form
        v-if="isShowAddForm"
        :model="form"
        ref="formvc"
        status-icon
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题">
          <el-input
            type="text"
            v-model="form.title"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="所属分类">
          <el-select v-model="form.cate_id" placeholder="请选择">
            <el-option
              v-for="item in cates"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="封面图">
          <img
            v-if="imageUrl"
            :src="imageUrl"
            @click="selectCover"
            width="100px"
            height="100px"
          />
          <span
            v-else
            class="el-icon-upload"
            style="font-size: 40px; cursor: pointer"
            @click="selectCover"
          ></span>
        </el-form-item>
        <el-form-item label="内容">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :mode="mode"
            />
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="form.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowAddForm = false">取 消</el-button>
        <el-button type="primary" @click="addArticle">添加</el-button>
      </span>
    </el-dialog>

    <!-- 选择附件的对话框 -->
    <el-dialog
      title="选择附件"
      :destroy-on-close="true"
      :visible.sync="isShowAddMedia"
    >
      <!-- 防止媒体组件media -->
      <media :media-data="mediaData" @click="clickImg" is-show-mask />
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelSelect">取消选择</el-button>
        <el-button type="primary" @click="confirmSelect">确定选择</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import { reqGetArticle, reqGetCate, reqAddArticle, reqGetMedia } from '@/api'
import media from '@/components/media'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
export default {
  data() {
    return {
      editor: null,
      //   编辑器配置
      editorConfig: {
        placeholder: '请输入内容...',
        readOnly: false,
        MENU_CONF: {
          lineHeight: ['1', '1.5', '2', '2.5', '3.5'],
          uploadImage: {
            server: this.$API + '/upload',
            fieldName: 'file',
            maxFileSize: 2 * 1024 * 1024, // 2m
            maxNumberOfFiles: 3,
            allowedFileTypes: ['image/*'],
            headers: {
              token: this.$store.state.token,
            },
            onBeforeUpload(file) {
              console.log('上传之前')
              return file
            },
            onSuccess(file, res) {
              console.log(`${file.name} 上传成功`, res)
            },
            onError(file, err, res) {
              console.log(`${file.name} 上传出错`, err, res)
            },
            customInsert: (res, insertFn) => {
              console.log('customInsert', res)
              let { path } = res
              path = this.$API + '/' + path
              insertFn(path)
            },
          },
        },
      },
      mode: 'default', // or 'simple'
      imageUrl: '',
      media: {}, // 记录单击附件选择的图片信息
      mediaData: [],
      isShowAddMedia: false,
      form: {
        title: '',
        cate_id: 0,
        content: '',
      },
      isShowAddForm: false,
      input: '',
      page: 1,
      pagesize: 3,
      tableData: [],
      total: 0,
      cates: [],
    }
  },
  async mounted() {
    this.loadArticle()
  },
  methods: {
    // 展示文章详情：
    async showContent(article) {
      try {
        await this.$alert(article.content, article.title, {
          dangerouslyUseHTMLString: true,
        })
      } catch (err) {}
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      // 查看所有的配置key
      //   console.log(this.editor.getAllMenuKeys())
    },
    // 确认选择附件
    confirmSelect() {
      // a: 获取附件的id和图片路径
      console.log('confirmSelect：', this.media)
      // b: 关闭附件弹框
      this.isShowAddMedia = false
      // c: 预览
      this.imageUrl = this.media.path_url
      this.mediaID = this.media.id
    },
    // 取消选择附件
    cancelSelect() {
      // a: 关闭附件弹框
      this.isShowAddMedia = false
      // b: media置空
      this.media = {}
      this.imageUrl = ''
    },

    // 选择一个图片
    clickImg(item) {
      console.log('click', item)
      // 存储选中图片的信息
      this.media = item
    },
    // 单击选择一个封面
    async selectCover() {
      // 展示添加附件的对话框
      this.isShowAddMedia = true
      // 获取附件数据
      let mediaData = await reqGetMedia()
      mediaData = mediaData.map((item) => {
        item.path_url = this.$API + '/' + item.path_url
        return item
      })
      this.mediaData = mediaData
    },
    // 发请求添加文章
    async addArticle() {
      if (this.form.cate_id === 0) {
        this.$message({
          message: '请选择一个分类',
          type: 'warning',
        })
        return
      }

      // 1. 收集表单数据
      let cover_id = this.media.id || 0
      // 2. 发送请求
      let { code, message } = await reqAddArticle({ ...this.form, cover_id })
      // 3. 成功：a: 关闭弹框 b:重新加载文章列表
      this.$message(message)
      if (code === 20000) {
        this.isShowAddForm = false
        this.loadArticle()
        // 4. 清空表单项
        console.log('@@@@@@@@@@@@@@@', this.$refs['formvc'])
        this.form = {} // 方案1：清空表单
      }
    },
    // 添加文章的对话框
    async addArticleDialog() {
      // 显示弹框
      this.isShowAddForm = true
      // 获取分类数据
      let cates = await reqGetCate()
      cates.unshift({ id: 0, cate_name: '请选择' })
      this.cates = cates
    },
    // 重置
    reset() {
      this.input = ''
      this.page = 1
      this.loadArticle()
    },
    // 搜索
    search() {
      // 1. 获取输入的值
      // 2. 页码置为1
      this.page = 1
      // 3. 发请求获取查询数据 （携带输入的值input）
      this.loadArticle()
    },
    // 点击分页
    async pageClick(page) {
      this.page = page
      this.loadArticle()
    },

    // 获取分页的文章数据
    async loadArticle() {
      let params = {
        page: this.page,
        pagesize: this.pagesize,
        input: this.input,
      }
      let { count, data } = await reqGetArticle(params)
      this.total = count
      this.tableData = data
    },
  },
  components: {
    media,
    Editor,
    Toolbar,
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
}
</script>

<style lang="scss" scoped>
.article-container {
  .header {
    display: flex;
    align-items: center;
    padding: 4px;

    .search {
      display: flex;
      margin-left: 20px;
    }

    .add {
      height: 40px;
    }
  }
}
</style>
